package com.fmboy.MXH.nav.controller;

import cn.hutool.core.bean.BeanUtil;
import com.fmboy.MXH.nav.domain.ErrorCode;
import com.fmboy.MXH.nav.domain.Result.Result;
import com.fmboy.MXH.nav.domain.Result.ResultToken;
import com.fmboy.MXH.nav.domain.dto.PasswordResetDTO;
import com.fmboy.MXH.nav.domain.dto.UserDTO;
import com.fmboy.MXH.nav.domain.entities.FileResponse;
import com.fmboy.MXH.nav.domain.entities.User;
import com.fmboy.MXH.nav.domain.pojo.UserVO;
import com.fmboy.MXH.nav.service.impl.FileService;
import com.fmboy.MXH.nav.service.impl.UserServiceImpl;
import com.fmboy.MXH.nav.utils.JwtTool;
import com.fmboy.MXH.nav.utils.UserContext;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.ValidationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.time.Duration;
import java.util.List;

@CrossOrigin
@Slf4j
@Tag(name = "用户接口", description = "User API")
@RestController
@RequestMapping("/mxh-nav")
public class UserController {
    @Resource
    private FileService fileService;
    @Resource
    private UserServiceImpl userService;

    @Value("${mxh.tokenTime}")
    private int tokenTime;

    @Resource
    private JwtTool jwtTool;

    // 用户注册
    @PostMapping("register")
    @Operation(summary = "用户注册", description = "用户注册")
    public Result<String> register(@RequestBody UserDTO userDTO) {
        try {
            userService.register(userDTO);
            log.info("用户注册成功");
            return Result.success("操作成功");

        } catch (ValidationException e) {
            log.error("用户注册失败: {}", e.getMessage(), e);
            if (e.getMessage().equals("注册失败，用户名已存在！")) {
                return Result.error(ErrorCode.CONFLICT, e.getMessage());
            }
            if (e.getMessage().equals("注册失败, 验证码错误!")) {
                return Result.error(ErrorCode.INVALID_REQUEST, e.getMessage());
            }
            if (e.getMessage().equals("注册失败，用户名不符合规定！")) {
                return Result.error(ErrorCode.INVALID_REQUEST, e.getMessage());
            }
            if (e.getMessage().equals("注册失败，该邮箱已注册！")) {
                return Result.error(ErrorCode.CONFLICT, e.getMessage());
            }
            return Result.error(ErrorCode.INVALID_REQUEST, e.getMessage());
        }
    }

    // 用户登录
    @Operation(summary = "用户登录", description = "用户登录")
    @PostMapping("login")
    public ResultToken login(@RequestBody UserDTO userDTO) {

        try {

            UserVO login = userService.login(userDTO);

            // 使用 JwtTool 生成 JWT
            String token = jwtTool.createToken(login.getId(), Duration.ofHours(tokenTime), login.getEmail(), login.getRole());
            log.info("用户登录成功");

            return ResultToken.success(token);
        } catch (ValidationException e) {
            return ResultToken.error(e.getMessage(), ErrorCode.UNAUTHORIZED.getCode());
        }
    }
    // 用户重置密码

    @Operation(summary = "用户重置密码", description = "用户重置密码")
    @PostMapping("/password/reset")
    public Result<String> Token(@RequestBody PasswordResetDTO passwordResetDTO) {
        try {
            userService.PasswordReset(passwordResetDTO);
            return Result.success("重置密码成功！");
        } catch (ValidationException e) {
            if (e.getMessage().equals("验证码错误！")) {
                return Result.error(ErrorCode.INVALID_REQUEST, e.getMessage());
            }
            if (e.getMessage().equals("重置密码失败，该邮箱未注册！")) {
                return Result.error(ErrorCode.NOT_FOUND, e.getMessage());
            }
            return Result.error(ErrorCode.PASSWORD_INCORRECT, e.getMessage());
        }
    }

    //获取-用户基本信息
    @Operation(summary = "获取-用户基本信息", description = "获取-用户基本信息")
    @GetMapping("/user/info")
    public Result<UserVO> getUserInfo() {
        Long userId = UserContext.getUserId();
        User byId = userService.getById(userId);
        UserVO userVO = new UserVO();
        BeanUtil.copyProperties(byId, userVO);
        userVO.setCreate_time(byId.getCreateTime());
        userVO.setUpdate_time(byId.getUpdateTime());
        return Result.success("获取成功！", userVO);
    }

    //修改-头像
    @Operation(summary = "修改-头像", description = "修改-头像")
    @PatchMapping("/update/avatar")
    public Result<String> updateAvatar(@RequestParam("avatar") MultipartFile[] files, HttpServletRequest request) {
        try {
            List<FileResponse> fileResponses = fileService.uploadFiles(files, request);
            //  将文件路径存在数据库中
            userService.updateAvatar(fileResponses.get(0).getFileUrl());
            return Result.success("修改成功！");
        } catch (Exception e) {
            return Result.error(ErrorCode.INVALID_REQUEST, e.getMessage());
        }
    }

    //修改-基本资料
    @Operation(summary = "修改-基本资料", description = "修改-基本资料")
    @PatchMapping("/update/info")
    public Result<String> updateInfo(@RequestBody UserDTO userDTO) {
        try {
            Long userId = UserContext.getUserId();
            User user = new User();
            BeanUtil.copyProperties(userDTO, user);
            user.setId(Math.toIntExact(userId));
            userService.updateById(user);
            return Result.success("修改成功！");
        } catch (Exception e) {
            return Result.error(ErrorCode.INVALID_REQUEST, "修改失败，昵称不能为空！");
        }
    }

    //修改-用户名
    @Operation(summary = "修改-用户名", description = "修改-用户名")
    @PatchMapping("/update/username")
    public Result<String> updateUsername(@RequestBody UserDTO userDTO, HttpServletRequest request) {
        try {
            Long userId = UserContext.getUserId();
            User user = new User();
            BeanUtil.copyProperties(userDTO, user);
            user.setId(Math.toIntExact(userId));
            user.setEmail(jwtTool.getEmail(request));
            // 获取用户邮箱

            userService.updateByIdName(user, userDTO.getVerification_code());
            return Result.success("修改成功！");

        } catch (ValidationException e) {
            if (e.getMessage().equals("修改失败，用户名已存在！")) {
                return Result.error(ErrorCode.CONFLICT, e.getMessage());
            }
            if (e.getMessage().equals("修改失败，用户名不符合规定！")) {
                return Result.error(ErrorCode.INVALID_REQUEST, e.getMessage());
            }
            if (e.getMessage().equals("验证码错误！")) {
                return Result.error(ErrorCode.INVALID_REQUEST, e.getMessage());
            }
            return Result.error(e.getMessage());
        }
    }

    //修改-邮箱
    @Operation(summary = "修改-邮箱", description = "修改-邮箱")
    @PatchMapping("/update/email")
    public Result<String> updateEmail(@RequestBody UserDTO userDTO) {
        try {
            User user = new User();
            BeanUtil.copyProperties(userDTO, user);
            user.setId(Math.toIntExact(UserContext.getUserId()));
            userService.updateEmail(user, userDTO.getVerification_code());
            return Result.success("修改成功！");
        } catch (ValidationException e) {
            if (e.getMessage().equals("修改失败，此邮箱已被绑定！")) {
                return Result.error(ErrorCode.EMAIL_ALREADY_BOUND, e.getMessage());
            }
            return Result.error(ErrorCode.INVALID_REQUEST, e.getMessage());
        }
    }

    //修改-密码
    @Operation(summary = "修改-密码", description = "修改-密码")
    @PatchMapping("/update/password")
    public Result<String> updatePassword(@RequestBody UserDTO userDTO) {
        try {
            userService.updatePassword(userDTO);
            return Result.success("修改成功！");
        } catch (ValidationException e) {
            return Result.error(ErrorCode.INVALID_REQUEST, e.getMessage());
        }

    }
}
